package com.atguigu.gmall.user.service.impl;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.Jsons;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.user.entity.UserInfo;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.vo.UserLoginSuccessVo;
import com.atguigu.gmall.user.vo.UserLoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* @author lfy
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2022-10-14 09:31:11
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public UserLoginSuccessVo login(UserLoginVo vo) {

        // 去数据库查询
        String encrypt = MD5.encrypt(vo.getPasswd());
        UserInfo info = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getLoginName, vo.getLoginName())
                .eq(UserInfo::getPasswd, encrypt)
        );

        // 数据库无此用户
        if (info == null){
            throw new GmallException(ResultCodeEnum.USER_PWD_INVAILD);
        }

        // 登录成功
        UserLoginSuccessVo successVo = new UserLoginSuccessVo();
        String token = UUID.randomUUID().toString().replace("-", "");
        successVo.setToken(token);
        successVo.setNickName(info.getNickName());

        // redis共享用户信息
        redisTemplate.opsForValue().set(RedisConst.USER_LOGIN + token, Jsons.toStr(info),7,TimeUnit.DAYS);


        return successVo;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(RedisConst.USER_LOGIN + token);
    }
}




